/**
 * Created by 追风少年 on 2018/6/7.
 */

var UserInput = {
    URL:{
        ADD_URL:'/admin/sysUser/add',
        UPDATE_URL:'/admin/sysUser/update',
        FIND_USER_INFO_URL:"/admin/sysUser/findUserInfoById",
        FIND_ALL_ROLE_URL:"/admin/role/findAllRole"
    }
};

app.controller('userInputController', function($scope,$http,$q) {

    $scope.flowTypeList = [];
    $scope.allRoles = [];
    $scope.userInfo = {};

    $scope.entity = {
        fullname:"",
        cellphone:""
    };
    $scope.submitUrl = UserInput.URL.ADD_URL;
    $scope.isUpdate = false;

    // 页面加载完成
    $scope.load = function(){
        var id = $("#userId").val();
        // $scope.getRoles();
        // $scope.initValue();
        if(id != "none"){ // is update page
            $scope.submitUrl = UserInput.URL.UPDATE_URL;
            $scope.isUpdate = true;
        }else{
            // $scope.initRoleCheckBox();
        }
    };

    // 初始化角色选择框
    $scope.initRoleCheckBox = function(){
        var checkBoxDiv = $("#roleDiv");
        for(var i = 0; i < $scope.allRoles.length; i++){
            var role = $scope.allRoles[i];
            if(role.checked){
                checkBoxDiv.append('<input checked="" value="'+role.roleid+'" type="checkbox" name="role" title="'+role.rolename+'">');
            }else{
                checkBoxDiv.append('<input value="'+role.roleid+'" type="checkbox" name="role" title="'+role.rolename+'">');
            }
        }
        layui.use('form', function(){
            var form = layui.form;
            //各种基于事件的操作，下面会有进一步介绍
            form.render('checkbox');
            form.val("inputForm", {

            });
        });
    };

    // 获取所有的角色
    function getAllRole() {
        return $q(function (resolve, reject) {
            $http.post(UserInput.URL.FIND_ALL_ROLE_URL,{}).success(function(data,status,headers,config){
                console.log(data);
                if(data.status){
                    $scope.allRoles = data.data;
                    resolve("getAllRole successful");
                }else{
                    console.error(data);
                    reject("getAllRole fail");
                    alert("数据加载失败,请联系管理员");
                }
            }).error(function(data,status,headers,config){
                console.error(data);
                reject("getAllRole fail");
            });
        })
    }

    // 获取编辑的用户数据
    function getUserInfo() {
        return $q(function (resolve, reject) {
            var id = $("#userId").val();
            if(id == "none"){
                resolve("getUserInfo successful");
                return false;
            }
            $http.post(UserInput.URL.FIND_USER_INFO_URL,{id:id}).success(function(data,status,headers,config){
                console.log("getUserInfo数据请求成功");
                console.log(data);
                if(data.status){
                    $scope.userInfo = data.data;
                    resolve("getUserInfo successful");
                }else{
                    console.error(data);
                    reject("getUserInfo fail");
                    alert("数据加载失败,请联系管理员");
                }
            }).error(function(data,status,headers,config){
                console.error(data);
                reject("getUserInfo fail");
            });
        });
    }

    $q.all([getAllRole(), getUserInfo()])
        .then(function (dataArr) {
            //promise都成功执行后的回调函数
            // console.log("$q.all: ", dataArr);
            // console.log($scope.allRoles);
            // console.log($scope.userInfo);
            if($scope.userInfo.userInfo){
                $scope.entity = $scope.userInfo.userInfo;
                var userRoles = $scope.userInfo.roles;
                for (var i = 0; i<userRoles.length; i++){
                    for (var j=0;j<$scope.allRoles.length;j++){
                        if(userRoles[i].roleid == $scope.allRoles[j].roleid){
                            $scope.allRoles[j].checked = true;
                        }
                    }
                }
            }
            $scope.initRoleCheckBox();
        }, function (err) {
            console.log("$q.all: ", err)
        });

    $scope.validateParam = function(){
        //
        // if(Utils.isNull($scope.entity.fullname)){
        //     layer.msg("请填写用户名称");
        //     return false;
        // }
        if(Utils.isNull($scope.entity.cellphone)){
            layer.msg("请填写用户手机号");
            return false;
        }
        var roles = Utils.getCheckBoxNameAndVal("role");
        $scope.entity.roleIds = "";
        if(roles.length == 0){
            layer.msg("请选择用户角色");
            return false;
        }
        for (var i = 0; i < roles.length; i++){
            if(i>0){
                $scope.entity.roleIds += ",";
            }
            $scope.entity.roleIds += roles[i].value;
        }
        return true;
    };

    $scope.submit = function($event){
        if(!$scope.validateParam()){ // 校验参数
            return false;
        }
        var btn = $event.target;
        btn.disabled = true;
        $http.post($scope.submitUrl,$scope.entity).success(function (ret) {
            console.log(ret);
            if(ret.status){
                layer.alert(ret.msg, {
                    icon: 1,
                    skin: 'layer-ext-moon',
                    yes:function(index){
                        layer.close(index);
                        parent.closeWinAndFlush();
                    }
                });
            }else{
                layer.msg(ret.msg);
                btn.disabled = false;
                return;
            }
        }).error(function(ret){
            btn.disabled = false;
            console.error("err:"+ret);
        });

    };

});